package afaas.framework.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertyUtil {

    private static final Map<String, Properties> PROPERTIES_MAP = new HashMap<>();

    public static <T> T get(String key, String filePath, Class<T> clz)  {
        CheckUtil.checkArgument(key != null && !"".equals(key));
        CheckUtil.checkArgument(filePath != null && !"".equals(filePath));

        Properties properties = get(filePath);
        return LangUtil.convert(properties.get(key), clz);
    }

    public static Properties get(String filePath){
        Properties properties = PROPERTIES_MAP.get(filePath);
        if(properties == null){
            try {
                FileInputStream fileInputStream = new FileInputStream(filePath);
                InputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

                Properties firstLoadedProperties = new Properties();
                firstLoadedProperties.load(bufferedInputStream);

                bufferedInputStream.close();
                fileInputStream.close();

                PROPERTIES_MAP.put(filePath, firstLoadedProperties);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            properties = PROPERTIES_MAP.get(filePath);
            CheckUtil.checkNotNull(properties);
        }
        return properties;
    }

}
